package zhoufu.sz.sanxiao_check.ui.basic;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.List;

import javax.inject.Inject;

import zhoufu.sz.sanxiao_check.R;
import zhoufu.sz.sanxiao_check.databinding.ActivityBasicMsgItem1Binding;
import zhoufu.sz.sanxiao_check.event.Event;
import zhoufu.sz.sanxiao_check.event.RxBus;
import zhoufu.sz.sanxiao_check.inject.HasComponent;
import zhoufu.sz.sanxiao_check.inject.components.DaggerLoginComponet;
import zhoufu.sz.sanxiao_check.inject.components.LoginComponet;
import zhoufu.sz.sanxiao_check.models.ReseauModel;
import zhoufu.sz.sanxiao_check.models.UpdateStreetInfoModel;
import zhoufu.sz.sanxiao_check.presents.BasicMsgItem1Presenter;
import zhoufu.sz.sanxiao_check.ui.CaptureActivity;
import zhoufu.sz.sanxiao_check.ui.MapActivity;
import zhoufu.sz.sanxiao_check.ui.adapter.WangGeAdapter;
import zhoufu.sz.sanxiao_check.ui.contract.BasicMsgItem1Contract;
import zhoufu.sz.sanxiao_check.utils.TextUtils;
import zhoufu.sz.sanxiao_check.utils.UIUtils;

/**
 * User:RCP
 * email:ruancaipu@gmail.com
 * Date:2016/7/25
 * 场所基本信息
 * //
 */
public class BasicMsgItem1Activity extends BaseMsgActivity
        implements HasComponent<LoginComponet>, AdapterView.OnItemClickListener,
        View.OnClickListener, BasicMsgItem1Contract.View {
    ActivityBasicMsgItem1Binding _binding;

    private WangGeAdapter mLeftAdapter;

    private WangGeAdapter mRightAdapter;

    private PopupWindow mPopupWindow;

    @Inject
    BasicMsgItem1Presenter _presenter;

    LoginComponet loginComponet;
    private AlertDialog rangeDialog;

    @Override
    protected void initInject() {
        setTitle(R.string.title_basic_item7);

        loginComponet = DaggerLoginComponet.builder()
                .activityModule(getActivityModule())
                .appComponent(getAppComponent()).build();
        loginComponet.inject(this);
        _presenter.bindView(this);
        mLeftAdapter = new WangGeAdapter(this, null, R.layout.item_textview);
        mRightAdapter = new WangGeAdapter(this, null, R.layout.item_textview);
        _presenter.onStart();
    }

    @Nullable
    @Override
    protected android.databinding.DataBindingComponent setBindingComponent() {
        return LoginComponet.Instance.get();
    }

    @Override
    protected int setIndividualId() {
        return R.layout.activity_basic_msg_item1;
    }

    @Override
    protected void initAfterOnCreate(ViewDataBinding binding) {
        _binding = (ActivityBasicMsgItem1Binding) binding;
        _binding.setModel(mInfoModel);
        _binding.setOnClickListener(this);
        setTypeCheck(_binding.mRbType1, "1");
        setTypeCheck(_binding.mRbType2, "2");
        setTypeCheck(_binding.mRbType3, "3");
        setTypeCheck(_binding.mRbType21, "4");
        setTypeCheck(_binding.mRbType22, "5");
        setTypeCheck(_binding.mRbType23, "6");

    }

    private void setTypeCheck(RadioButton rb, String type) {
        rb.setChecked(type.equals(mInfoModel.getType()));
        rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RadioButton radioButton = (RadioButton) v;
                RadioGroup opRg = (RadioGroup) radioButton.getParent();
                if (opRg == _binding.mRgType) {
                    opRg = _binding.mRgType2;
                } else {
                    opRg = _binding.mRgType;
                }
                int checkedRadioButtonId = opRg.getCheckedRadioButtonId();
                if (checkedRadioButtonId != 1) {
                    opRg.clearCheck();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_save) {
            int checkedRadioButtonId = _binding.mRgType.getCheckedRadioButtonId();
            int checkedRadioButtonId2 = _binding.mRgType2.getCheckedRadioButtonId();
            String type = checkedRadioButtonId == R.id.mRbType1 ? "1" :
                    checkedRadioButtonId == R.id.mRbType2 ? "2" : checkedRadioButtonId == R.id.mRbType3 ? "3"
                            : checkedRadioButtonId2 == R.id.mRbType2_1 ? "4"
                            : checkedRadioButtonId2 == R.id.mRbType2_2 ? "5"
                            : checkedRadioButtonId2 == R.id.mRbType2_3 ? "6" : "1";
            mInfoModel.setType(type);
            int reLevel = _binding.rgLevel.getCheckedRadioButtonId();
            String level = reLevel == R.id.rb_level_a ? "A" : reLevel == R.id.rb_level_b ? "B" : "C";
            mInfoModel.setGrade(level);
            mInfoModel.setIsLicense(
                    _binding.mRgID.getCheckedRadioButtonId() == R.id.mRbID ? "1" : "0");
            if ("0".equals(mInfoModel.getIsLicense()) && !TextUtils.isEmpty(mInfoModel.getHas_Business())) {
                mInfoModel.setHas_Business("无");
            }
            _presenter.update(mInfoModel);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void popupShow(View view) {
        if (mPopupWindow == null) {
            View view1 = LayoutInflater.from(this).inflate(R.layout.layout_popup, null);
            ListView listView1 = (ListView) view1.findViewById(R.id.mListViewLeft);
            listView1.setOnItemClickListener(this);
            listView1.setAdapter(mLeftAdapter);
            ListView listView2 = (ListView) view1.findViewById(R.id.mListViewRight);
            listView2.setOnItemClickListener(this);
            listView2.setAdapter(mRightAdapter);
            mPopupWindow = new PopupWindow(view1,
                    UIUtils.getScreentWidth(this) - UIUtils.dip2px(100),
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow
                    .setBackgroundDrawable(getResources().getDrawable(R.drawable.regist_bg_circle));
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.showAsDropDown(view);
        } else {
            mPopupWindow.showAsDropDown(view);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.mListViewLeft:
                _presenter.checkLeft(position);
                break;
            case R.id.mListViewRight:
                ReseauModel model = _presenter.checkRight(position);
                mInfoModel.setDistrict_ID(model.getID());
                mInfoModel.setReseau_Type(model.getSuperID());
                _binding.mTvBasicMsgWangGe.setText(model.getSuperName() +"--"+ model.getName());
                _binding.tvAddress.setText(model.getName());
                mPopupWindow.dismiss();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mTvBasicMsgWangGe:
                popupShow(v);
                break;
            case R.id.mIvScanCode:
                Intent intent1 = new Intent(this, CaptureActivity.class);
                intent1.putExtra("zxing_code_id", "2");
                startActivityForResult(intent1, 0);
                break;
            case R.id.mIvScanAddress:
                intent1 = new Intent(this, CaptureActivity.class);
                intent1.putExtra("zxing_code_id", "3");
                startActivityForResult(intent1, 3);
                break;
            case R.id.mIvLocation:
                Intent intent2 = new Intent(this, MapActivity.class);
                intent2.putExtra(MapActivity.KEY_LONGITUDE, mInfoModel.getPlace_x());
                intent2.putExtra(MapActivity.KEY_LATITUDE, mInfoModel.getPlace_y());
                intent2.putExtra(MapActivity.KEY_ADDRESS, mInfoModel.getAddress());
                startActivityForResult(intent2, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == 0) {
                String code = data.getStringExtra("encoding_house");
                mInfoModel.setBuilding_No(code);
                _binding.mEtBuildNO.setText(code);
            } else if (requestCode == 3) {
                //房屋地址
                mInfoModel.setAddress(data.getStringExtra("encoding_house"));
            } else {
                double lon = data.getDoubleExtra(MapActivity.KEY_LONGITUDE, 0.0);
                double lat = data.getDoubleExtra(MapActivity.KEY_LATITUDE, 0.0);
                mInfoModel.setAddress(data.getStringExtra(MapActivity.KEY_ADDRESS));
                mInfoModel.setPlace_x(lon);
                mInfoModel.setPlace_y(lat);
            }
        }
    }

    @Override
    public void setLeftAdapter(List<ReseauModel> list) {
        mLeftAdapter.replaceAll(list);
    }

    @Override
    public void setRightAdapter(List<ReseauModel> list) {
        mRightAdapter.replaceAll(list);
    }

    @Override
    public void updateSuccese(UpdateStreetInfoModel model) {
        mInfoModel.setSID(model.getSID());
        mInfoModel.setRID(model.getRID());
        mInfoModel.setPlace_No(model.getPlace_No());
        RxBus.getDefault().post(new Event.UpdateStreetInfo(mInfoModel));
        finish();
    }

    @Override
    public void showToast(String msg) {
        UIUtils.showSnackbar(_binding.getRoot(), msg);
    }

    @Override
    public void pullFaild() {

    }

    @Override
    public void pullEnd() {
        hideProgreesDialog();
    }

    @Override
    public void pullStart() {
        showProgreesDialog();
    }


    @Override
    public LoginComponet getComponent() {
        return loginComponet;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        _presenter.onDestroy();
    }

    /**
     * 选择经验范围
     *
     * @param view
     */
    public void selectRange(final View view) {
        final String[] items = {"餐饮(使用燃气)", "餐饮(轻食)", "仓库", "麻将馆", "网吧", "废品站", "快递物流", "燃气服务店", "旅馆", "汽修店", "电动车销售及维修", "美容美发", "诊所", "新旧货家私电器", "五金", "小档口"
                , "小作坊-食品", "小作坊-非食品", "小娱乐场所"};
        rangeDialog = new AlertDialog.Builder(this).setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ((TextView)view).setText(items[which]);
                mInfoModel.setBusiness(items[which]);
            }
        }).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (rangeDialog != null)
            rangeDialog.dismiss();
    }
}
